package com.unittec.drainage.gateway.common;

import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

import org.apache.commons.lang3.StringUtils;
import org.springframework.core.ParameterizedTypeReference;

import com.unittec.drainage.provider.ApplicationContextProvider;
import com.unittec.drainage.provider.common.Md5;
import com.unittec.drainage.provider.common.ServiceFuncUtils;
import com.unittec.drainage.provider.scope.ThreadLocalScope;
import com.unittec.drainage.provider.service.HystrixRestTemplateService;
import com.unittec.drainage.sdk.auth.domain.SysApplicationDto;
import com.unittec.drainage.sdk.auth.request.Req101501;
import com.unittec.drainage.sdk.auth.request.Req101513;
import com.unittec.drainage.sdk.auth.response.Res101501;
import com.unittec.drainage.sdk.auth.response.Res101513;
import com.unittec.drainage.sdk.root.common.FieldConstants;
import com.unittec.drainage.sdk.root.domain.GatewayRequest;
import com.unittec.drainage.sdk.root.domain.Result;

/**
 * @Description:
 * @author: chenjiawang
 * @CreateDate: 2020/3/13 15:50
 */
public class ApplicationUtils {

    /**
     *
     */
    private static final String FIND_ALL_APPLICATION_URL = "http://drainage-auth-101/101513";
    /**
     * 查询单个
     */
    private static final String FIND_APPLICATION_URL = "http://drainage-auth-101/101501";

    /**
     *
     */
    private static final Map<String, SysApplicationDto> APP_MAP = new ConcurrentHashMap<>();

    /**
     *
     */
    private static HystrixRestTemplateService HYSTRIXRESTTEMPLATE_SERVICE = null;

    /**
     * @param ip
     * @param appId
     * @param appKey
     * @return
     */
    public static boolean checkAppId(String ip, String appId, String appKey) {
        if (StringUtils.isBlank(appId)) {
            throw new RuntimeException("appId为空");
        }
        if (StringUtils.isBlank(appKey)) {
            throw new RuntimeException("appKey 为空");
        }
        if (APP_MAP.size() == 0) {
            synchronized (ApplicationUtils.class) {
                if (APP_MAP.size() == 0) {
                    init();
                }
            }
        }
        SysApplicationDto sysApplicationDto = APP_MAP.get(appId);
        if (null == sysApplicationDto) {
            return findByAppId(ip, appId, appKey);
        }
        return true;
    }

    /**
     * 初始化
     */
    public static void init() {
        List<SysApplicationDto> all = findAll();
        if (all != null && all.size() > 0) {
            for (SysApplicationDto sysApplicationDto : all) {
                APP_MAP.put(sysApplicationDto.getAppCode(), sysApplicationDto);
            }
        }
    }

    private static void initHystrixRestTemplateService() {
        if (HYSTRIXRESTTEMPLATE_SERVICE == null) {
            synchronized (ServiceFuncUtils.class) {
                if (null == HYSTRIXRESTTEMPLATE_SERVICE) {
                    HYSTRIXRESTTEMPLATE_SERVICE = ApplicationContextProvider.getBean(HystrixRestTemplateService.class);
                }
            }
        }
    }

    /**
     * @return
     */
    private static List<SysApplicationDto> findAll() {
        GatewayRequest<Req101513> request = new GatewayRequest<>();
        Req101513 content = new Req101513();
        request.setContent(content);
        request.setMethod("101513");
        ThreadLocalScope.AuthData authData = ThreadLocalScope.getAuthData();
        initHystrixRestTemplateService();
        Result<Res101513> result =
            HYSTRIXRESTTEMPLATE_SERVICE.exchange(Md5.getMd5(FieldConstants.SYS_REQUEST_SOURCE_ID),
                FIND_ALL_APPLICATION_URL, request, authData, new ParameterizedTypeReference<Result<Res101513>>() {});
        if (result.isSuccess()) {
            return result.getData() == null ? null : result.getData().getObj();
        }
        return null;
    }

    /**
     * 获取单个
     *
     * @return
     */
    private static boolean findByAppId(String ip, String appId, String appKey) {
        GatewayRequest<Req101501> request = new GatewayRequest<Req101501>();
        request.setMethod("101501");
        request.setAppId(appId);
        Req101501 content = new Req101501();
        content.setIp(ip);
        content.setAppKey(appKey);
        content.setAppKey(appKey);
        content.setAppCode(appId);
        request.setContent(content);
        ThreadLocalScope.AuthData authData = ThreadLocalScope.getAuthData();
        if (StringUtils.isBlank(authData.getAppId())) {
            authData.setAppId(appId);
        }
        try {
            initHystrixRestTemplateService();
            Result<Res101501> result =
                HYSTRIXRESTTEMPLATE_SERVICE.exchange(Md5.getMd5(FieldConstants.SYS_REQUEST_SOURCE_ID),
                    FIND_APPLICATION_URL, request, authData, new ParameterizedTypeReference<Result<Res101501>>() {});
            if (result.isSuccess()) {
                Res101501 data = result.getData();
                if (data != null) {
                    SysApplicationDto sysApplicationDto = data.getObj();
                    if (sysApplicationDto != null) {
                        APP_MAP.put(sysApplicationDto.getAppCode(), sysApplicationDto);
                        return true;
                    }
                }
                return false;
            }
            throw new RuntimeException(result.getBizMsg());
        } catch (Exception e) {
            throw new RuntimeException(e.getLocalizedMessage());
        }
    }

}
